package com.watermark.core.utils;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

/**
 * context kit 封装
 */
public class UIKit {
    private static Application _mApplication;
    private final static Handler mainHand = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (null != sMessageHandler) {
                sMessageHandler.handleMessage(msg);
            }
        }
    };

    public static Context getContext() {
        if (null == _mApplication) {
            _mApplication = getInstanceFromReflexG();
        }
        return _mApplication;
    }

    /**
     * @return 是否运行在主线程
     */
    public static boolean isOnUIThread() {
        return Looper.myLooper() == Looper.getMainLooper();
    }

    /**
     * 运行主线程任务
     *
     * @param task 任务
     */
    public static void runOnUiThread(Runnable task) {
        if (null == task) return;
        if (Looper.myLooper() == Looper.getMainLooper()) {
            task.run();
        } else {
            mainHand.post(task);
        }
    }

    public static void runOnUiThread(Runnable task, long delay) {
        if (delay > 0) {
            mainHand.postDelayed(task, delay);
        } else {
            runOnUiThread(task);
        }
    }

    public static void removeTask(Runnable task) {
        if (null != task) mainHand.removeCallbacks(task);
    }

    private static Application getInstanceFromReflexG() {
        Application application = null;
        try {
            application = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
            if (application == null) {
                throw new IllegalStateException("Static initialization of Applications must be on main thread.");
            }
        } catch (final Exception e) {
            try {
                application = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
            } catch (final Exception ex) {
                e.printStackTrace();
            }
        }
        return application;
    }

    public static MessageHandler sMessageHandler;

    public interface MessageHandler {
        void handleMessage(@NonNull Message msg);
    }
}
